import {observable, action} from 'mobx';
import { ListStore } from './listStore'
import { WeaTools } from 'ecCom';
import { WeaForm } from 'comsMobx';
import * as API_LIST from '../apis/totalBudget'
import * as API_HIS from '../apis/rptHistory'
import * as API_BASE from '../apis/fnaReportBase'
import { WeaLocaleProvider } from 'ecCom';
import {message} from 'antd';
import {WeaTableNew} from 'comsMobx'
const {TableStore} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

/**
 * 预算总额表的Store
 */
export class TotalBudgetStore extends ListStore{

	//高级搜索默认值
	@observable baseParams = {

    };

    //科目浏览按钮联动周期
    @observable feeperiod = '-1';

	//tab默认值
	@observable searchParams = {
        index:0
    };

    //图表数据
    chartsData = {};//图表数据清空

    //GUID
    guid = '';

    //保存模型的数据
    modalSaveParam = {
    	tbName:''
    };

    //保存报表的Modal的显隐
    @observable showModal = false;

    //保存报表的状态
    @observable saveFlag = false;

    //图表和列表按钮切换的状态
    @observable charFlag = false;
    
    //是否点击了高级搜索的状态
    @observable isSearch = false;
	
    //保存高级搜索的查询参数
    advSearchParam = {};

    //保存历史高级搜索的查询参数
    advHisSearchParam = {
        nameQuery:""
    };
    
    //图表浏览回显参数
    echarBrowser = {};

    //保存图表浏览按钮的orgId和orgIdName
    orgIdAndName = {};

    /** 图表查询 */
    @observable formChar = new WeaForm();
    @observable conditionChar = [];

    constructor(){
		super();
		this.title = "";
        this.pageType = 'TotalBudget';
        this.showShareModel = false;
		this.appendBaseParams = this.appendBaseParams.bind(this);
		this.initDatas = this.initDatas.bind(this);
		this.doSearch = this.doSearch.bind(this);
		this.initInfo = this.initInfo.bind(this);
		this.baseHisSearch = this.baseHisSearch.bind(this);
		this.setShowModal = this.setShowModal.bind(this);
		this.saveTempData = this.saveTempData.bind(this);
		this.historyDelete = this.historyDelete.bind(this);
		this.generGUID = this.generGUID.bind(this);
		this.saveModelInfo = this.saveModelInfo.bind(this);
		this.setModalSaveParam = this.setModalSaveParam.bind(this);
		this.setShareModalVisible = this.setShareModalVisible.bind(this);
		this.setSaveFlag = this.setSaveFlag.bind(this);
		this.setCharFlag = this.setCharFlag.bind(this);
        this.setIsSearch = this.setIsSearch.bind(this);
        this.saveGUID = this.saveGUID.bind(this);
		this.setAdvSearchParam = this.setAdvSearchParam.bind(this);	
		this.initECharInfo = this.initECharInfo.bind(this);
        this.setFeeperiod = this.setFeeperiod.bind(this);
	}

	@action
    appendBaseParams(params) {
        this.baseParams = {...this.baseParams,...params};
    }

	initDatas(params = {}){
		this.initInfo("init");
		let value = Object.assign({},{
				qryFunctionType:0,
				rptViewType:0
			});

		this.doSearch(value);
	}

	//初始化高级搜索
	initInfo(value,params = {}){
		API_LIST.totalBudgetInfoP(params).then(data =>{
            if(data.flag == 'success'){
                this.hasRight = 1;

                const { conditions } = data;
                this.condition = conditions;
                this.form = new WeaForm();
                this.form.initFormFields(conditions);
                if(value=="init"){
                    //初始化tab列表  
                    let tabTitle = [{title:getLabel(24616,'查询报表'),key:0},{title:getLabel(82503,'历史查询结果'),key:1}];
                    this.topTab = tabTitle;
                    this.topTabCount = 2;
                    this.setShowSearchAd(true);

                    setTimeout(()=>{
                        const { subjectIds } = this.form.getFormParams();;
                        API_BASE.getSubjectFeeperiod({'subjectIds':subjectIds}).then(data =>{
                            this.setFeeperiod(data.feeperiod);
                        });   
                    },0);
                }else if(value.flag){
                    API_BASE.getSubjectFeeperiod(params).then(data =>{
                        let feeperiod = data.feeperiod;
                        this.setFeeperiod(data.feeperiod);
                        this.hisAdvViewBack(value);
                     }); 
                }
            } else {
                this.hasRight = 4;
            }
		});	
	}

    //初始化图表高级搜索
    initECharInfo(value){
        API_LIST.budgetECharInfo(value).then(data =>{
            if(data.flag == 'success'){
                this.hasRight = 1;

                const { conditions } = data;
                this.conditionChar = conditions;
                this.formChar = new WeaForm();
                this.formChar.initFormFields(conditions);
            } else {
                this.hasRight = 4;
            }
        }); 
    }

	//保存临时数据
	saveTempData(params = {},callback){
		const searchParamsAd = this.form.getFormParams();
		const newParams = { ...this.baseParams, ...searchParamsAd, ...params };
        this.loading = true; 
		API_LIST.saveTotalBudgetTempData(newParams).then(data =>{
            let result = JSON.parse(data.resultJson)
            if(result.flag){
                callback && callback();
            } else {
                message.error(result.msg);
                this.isSearch = false;
            }
		});
	}
    
	//TABLE数据
	doSearch(params = {},flag = true,callback) {
		if(this.searchParams.index==0){//报表查询的搜索
            const searchParamsAd = this.form.getFormParams();
            const newParams = { ...this.baseParams, ...searchParamsAd, ...params };
			this.loading = true; 
			API_LIST.totalBudgetReportP(newParams).then(data =>{
                if(data.flag == 'success'){
                    this.hasRight = 1;
    				if(newParams.rptViewType == 0){
                        this.tableStore = new TableStore();
                        if(flag){//回到第一页
                            this.tableStore.getDatas(data.datas,1);
                        }else{
                            this.tableStore.getDatas(data.datas);
                        }					
    	            	this.dataKey = data.datas;
                        this.chartsData = {};//图表数据清空
    				}else if(newParams.rptViewType == 1){
    					this.chartsData=data.datas;
                    }
                    
                    callback && callback();
                } else {
                    this.hasRight = 4;
                }
                this.loading = false; 
			});
		}else{//历史记录的高级搜索
            const searchParamsAd = this.formHis.getFormParams();
			let nameQuery = searchParamsAd.advQryName;
			const value = Object.assign({},searchParamsAd,{
	    		nameQuery:typeof(nameQuery)=='undefined'?'':nameQuery,
	    		rptTypeName:'fanRptTotalBudget'
    		});
            this.advHisSearchParam = value;
			this.queryHistoryData(value);     
		}
	}

	//基础搜索
    baseHisSearch(params = {}){
    	
    	this.queryHistoryData(params);
    }

    //历史记录删除
    historyDelete(params){
    	API_HIS.historyDelete(params).then(data=>{
            if(data.flag == 'success'){
                this.hasRight = 1;
                this.queryHistoryData({rptTypeName:'fanRptTotalBudget'},false);
            }else{
                this.hasRight = 4;
            }
    	});
    }

    //生成GUID
    generGUID(func){
    	API_HIS.getGUIDP().then(data=>{
            this.guid = data.guid;
            func && func();//外部的回调,防止程序速度，快与XHR
    	});
    }
    
    //在查询中打开高级搜索数据回显
    hisAdvViewBack = (params) =>{
        let obj = [];
        let subobj = [];
        let param = [];
        let ids = [];
        let names = [];
        let index=0;
        if(typeof(params.orgId)!="undefined" && params.orgId!=""){
            ids = params.orgId.split(',');
            names = params.orgIdName.split(',');
            for(;index<ids.length;index++){
            obj.push({id:ids[index],name:names[index]});
            }
        }
        param=[params.orgId,params.orgIdName,obj];
        if(typeof(params.subjectIds)!="undefined" && params.subjectIds!=""){
            ids = params.subjectIds.split(',');
            names = params.subjectName.split(',');
            for(let index=0;index<ids.length;index++){
                subobj.push({id:ids[index],name:names[index]});
            }
        }
        this.form.updateFields({
            orgType__orgId:{
                value:[
                params.orgType+'',
                param
                ],
                valueSpan:['orgId']
            },
            subjectIds: {
              value: params.subjectIds,
              valueSpan: params.subjectName,
              valueObj:subobj
            },
            sumSubOrg:{
                value: params.sumSubOrg
            },
            fnayear:{
                value:params.fnayear
            },
            groupFeeperiod:{
                value:params.groupFeeperiod+'',
            }
            });
    }

    //保存GUID
    saveGUID(value){
        this.guid = value;
    }

    //保存momal的显隐
    @action
    setShowModal(bool){
    	this.showModal = bool;
    }

    //保存报表
    saveModelInfo(params){
        this.loading = true;
    	API_HIS.saveReportP(params).then(data=>{
            if(data.flag == 'success'){
                this.hasRight = 1;
        		if(this.searchParams.index == '1'){
        			this.baseHisSearch({rptTypeName:'fanRptTotalBudget'});//刷新
        		}
        		//保存状态
        		this.saveFlag = true;
            }else{
                this.hasRight = 4;
            }
            this.loading = false;  
    	});
    }

    //保存momal的数据
    setModalSaveParam(params){
    	this.modalSaveParam = {...this.modalSaveParam,...params};
    }

    //清除Echar的form
    clearEcharFormFields = () =>{
        this.formChar.resetConditionValue();//清除查询条件值
    }

    //是否显示保存查询结果按钮
    @action 
    setSaveFlag(bool){
    	this.saveFlag = bool;
    }

    //图表与列表的切换
    @action 
    setCharFlag(bool){
    	this.charFlag = bool;
    }

    //是否点击了高级搜索
    @action 
    setIsSearch(bool){
    	this.isSearch = bool;
    }

    //保存高级搜索数据
    setAdvSearchParam(value){
        this.advSearchParam = value;
    }   

    //设置图表数据
    setChartsData = (value) => {
        this.chartsData = value;
    }

    //设置历史高级搜索的查询参数
    setAdvHisSearchParam = (value) => {
        this.advHisSearchParam = value;
    }

    //设置周期
    setFeeperiod = (value) => {
        this.feeperiod = value;
    }

    //数据重置，防止存留数据导致的页面显示不正常
    resetData = () => {
        this.tabKey = 0;

        this.showShareModel = false;

        //高级搜索默认值
        this.baseParams = {

        };

        //科目浏览按钮联动周期
        this.feeperiod = '-1';

        //tab默认值
        this.searchParams = {
            index:0
        };

        //图表数据
        this.chartsData = {};//图表数据清空

        //GUID
        this.guid = '';

        //保存模型的数据
        this.modalSaveParam = {
            tbName:''
        };

        //保存报表的Modal的显隐
        this.showModal = false;

        //保存报表的状态
        this.saveFlag = false;

        //图表和列表按钮切换的状态
        this.charFlag = false;
        
        //是否点击了高级搜索的状态
        this.isSearch = false;
        
        //保存高级搜索的查询参数
        this.advSearchParam = {};

        //保存历史高级搜索的查询参数
        this.advHisSearchParam = {
            nameQuery:""
        };
        
        //图表浏览回显参数
        this.echarBrowser = {};

        //保存图表浏览按钮的orgId和orgIdName
        this.orgIdAndName = {};
    }
}
